<?php
/**
 * [YIZHIKEJI System] Copyright (c) 2014 yz929.cn
 * YIZHIKEJI is NOT a free software, it under the license terms, visited http://www.yz929.cn/ for more details.
 */
defined('IN_IA') or exit('Access Denied');
$_W['page']['title'] = '站点管理 - 微站功能';
uni_user_permission_check('site_multi_display');
load()->model('site');
load()->func("qrcode");
$dos = array('display', 'post', 'del', 'default', 'copy', 'enable');
$do = in_array($do, $dos) ? $do : 'display';

if($do == 'post') {
    if (!$_W['isfounder'] && is_error($permission = uni_create_permission($_W['uid']))) {
        message($permission['message'], '' , 'error');
    }
    uni_user_permission_check('site_multi_post');
    $multiid = $_GPC['multiid'];
    if(!empty($multiid)) {
        $multi = pdo_fetch('SELECT * FROM ' . tablename('site_multi') . ' WHERE uid = :uid AND id = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
        if(empty($multi)) {
            message('微站不存在或已删除', referer(), 'error');
        }
        $multi['site_info'] = iunserializer($multi['site_info']) ? iunserializer($multi['site_info']) : array();
    }
    $sql = 'SELECT `s`.*, `t`.`name` AS `tname`, `t`.`title` FROM ' . tablename('site_styles') . ' AS `s` LEFT JOIN ' .
        tablename('site_templates') . ' AS `t` ON `s`.`templateid` = `t`.`id` WHERE `s`.`uid` = :uid';
    $styles = pdo_fetchall($sql, array(':uid' => $_W['uid']), 'id');
    $multi['style'] = $styles[$multi['styleid']];

    if(checksubmit('submit')) {
        if (checksubmit('submit')) {
            $data = array(
                'uid' => $_W['uid'],
                'title' => trim($_GPC['title']),
                'styleid' => intval($_GPC['styleid']),
                'status' => intval($_GPC['status']),
                'site_info' => iserializer(array(
                    'thumb' => $_GPC['thumb'],
                    'keyword' => $_GPC['keyword'],
                    'description' => $_GPC['description'],
                    'footer' => htmlspecialchars_decode($_GPC['footer'])
                )),
                'bindhost' => $_GPC['bindhost'],
            );
            if (empty($data['title'])) {
                message('请填写站点名称', referer(), 'error');
            }
//            if (!strcasecmp($_GPC['bindhost'],$_W['page']['copyright']['sitehost'])) {
//                message('请填写其他域名，不要填本平台域名（或者后台-站点设置域名项没填）！', referer(), 'error');
//            }
            if(!empty($multiid)) {
                pdo_update('site_multi', $data, array('id' => $multiid));
            } else {
                pdo_insert('site_multi', $data);
                $multiid = pdo_insertid();
                pdo_insert('uni_account_users', array('multiid' => $multiid, 'uid' => $_W['uid'], 'role' => 'owner'));
            }
            if (!empty($_GPC['keyword'])) {
                $cover = array(
                    'uid' => $_W['uid'],
                    'title' => $data['title'],
                    'keyword' => $_GPC['keyword'],
                    'url' => url('home', array('i' => $_W['uid'], 't' => $multiid)),
                    'description' => $_GPC['description'],
                    'thumb' => $_GPC['thumb'],
                    'module' => 'site',
                    'multiid' => $multiid,
                );
                site_cover($cover);
            }
            if (!empty($_FILES['headimg']['tmp_name'])) {
//                $_W['uploadsetting'] = array();
//                $_W['uploadsetting']['image']['folder'] = '';
//                $_W['uploadsetting']['image']['extentions'] = array('jpg');
//                $_W['uploadsetting']['image']['limit'] = $_W['config']['upload']['image']['limit'];
                load()->func("file");
                $upload = file_upload($_FILES['headimg'], 'image', "headimg_{$multiid}");
                if(is_error($upload)) {
                    message('头像保存失败,'.$upload['message'], referer(), 'info');
                } else {
                    $result = file_remote_upload($upload['path']);
                    if (!is_error($result) && $result !== false) {
                        file_delete($upload['path']);
                    }
                }
            }
//            qrcodeToAttachment("http://hyb.ittun.com//yizhi/app/index.php?c=home&multiid=".$multiid ,IA_ROOT . '/attachment/qrcode_'.$multiid.'.jpg');
            message('更新站点信息成功！', url('account/weizhan'), 'success');
        }
    }
    template('account/weizhan');
} else if($do == 'display') {
    $stat = weizhan_permission($_W['uid']);
    $templates = uni_templates();
    $multis = pdo_fetchAll('SELECT * FROM ' . tablename('site_multi') . ' WHERE uid = :uid', array(':uid' => $_W['uid']));
    foreach($multis as &$li) {
        $li['style'] = pdo_fetch('SELECT * FROM ' .tablename('site_styles') . ' WHERE uid = :uid AND id = :id', array(':uid' => $_W['uid'], ':id' => $li['styleid']));
        $li['template'] = pdo_fetch("SELECT * FROM ".tablename('site_templates')." WHERE id = :id", array(':id' => $li['style']['templateid']));
        $li['site_info'] = (array)iunserializer($li['site_info']);
        $li['url'] = $_W['siteroot'] . "app?multiid=" . $li['id'];
    }
    template('account/weizhan');
} else if($do == 'del') {
    uni_user_permission_check('site_multi_del');
    pdo_delete('site_nav', array('uid' => $_W['uid'], 'multiid' => $multiid));
    $rid = pdo_fetchcolumn('SELECT rid FROM ' .tablename('cover_reply') . ' WHERE uid = :uid AND multiid = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
    if(pdo_delete('rule', array('id' => $rid, 'uid' => $_W['uid'])) !== false) {
        pdo_delete('rule_keyword', array('rid' => $rid));
        pdo_delete('cover_reply', array('rid' => $rid, 'multiid' => $multiid));
        pdo_delete('stat_rule', array('rid' => $rid));
        pdo_delete('stat_keyword', array('rid' => $rid));
    }
    pdo_delete('site_multi', array('uid' => $_W['uid'], 'id' => $multiid));
    message('删除微站成功', referer(), 'success');
} else if($do == 'copy') {
    $multi = pdo_fetch('SELECT * FROM ' . tablename('site_multi') . ' WHERE uid = :uid AND id = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
    if(empty($multi)) {
        message('微站不存在或已删除', referer(), 'error');
    }
    $multi['title'] = $multi['title'] . '_' . random(6);
    unset($multi['id']);
    pdo_insert('site_multi', $multi);
    $multi_id = pdo_insertid();
    if(!$multi_id) {
        message('复制微站出错', '', 'error');
    } else {
        $navs = pdo_fetchall('SELECT * FROM ' . tablename('site_nav') . ' WHERE uid = :uid AND multiid = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
        if(!empty($navs)) {
            foreach($navs as &$nav) {
                unset($nav['id']);
                $nav['multiid'] = $multi_id;
                pdo_insert('site_nav', $nav);
            }
        }
        $cover = pdo_fetch('SELECT * FROM ' . tablename('cover_reply') . ' WHERE uid = :uid AND multiid = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
        if(!empty($cover)) {
            $rule = pdo_fetch('SELECT * FROM ' . tablename('rule') . ' WHERE uid = :uid AND id = :id', array(':uid' => $_W['uid'], ':id' => $cover['rid']));
            $keywords = pdo_fetchall('SELECT * FROM ' . tablename('rule_keyword') . ' WHERE uid = :uid AND rid = :id', array(':uid' => $_W['uid'], ':id' => $cover['rid']));
            if(!empty($rule) && !empty($keywords)) {
                $rule['name'] = $multi['title'] . '入口设置';
                unset($rule['id']);
                pdo_insert('rule', $rule);
                $new_rid = pdo_insertid();
                foreach($keywords as &$keyword) {
                    unset($keyword['id']);
                    $keyword['rid'] = $new_rid;
                    pdo_insert('rule_keyword', $keyword);
                }
                unset($cover['id']);
                $cover['title'] =  $multi['title'] . '入口设置';
                $cover['multiid'] =  $multi_id;
                $cover['rid'] =  $new_rid;
                pdo_insert('cover_reply', $cover);
            }
        }
        message('复制微站成功', url('account/weizhan', array('multiid' => $multi_id)), 'success');
    }
} else if($do == 'enable'){
    if(!empty($multiid)) {
        $multi = pdo_fetch('SELECT * FROM ' . tablename('site_multi') . ' WHERE uid = :uid AND id = :id', array(':uid' => $_W['uid'], ':id' => $multiid));
        if(empty($multi)) {
            message('微站不存在或已删除', referer(), 'error');
        }
    }
    if($multi[status] == 1){
        $multi[status] = 2;
    } else if($multi[status] == 2){
        $multi[status] = 1;
    }
    pdo_update("site_multi", $multi, array('id' => $multiid));
    message('操作成功', url('account/weizhan'), 'success');
}